package com.dingreading.cloud.admin.service.impl;

import com.dingreading.cloud.admin.entity.FreeDelivery;
import com.dingreading.cloud.admin.entity.table.FreeDeliveryTableDef;
import com.dingreading.cloud.admin.mapper.FreeDeliveryMapper;
import com.dingreading.cloud.admin.service.FreeDeliveryService;
import com.dingreading.cloud.common.util.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2024-07-03
 */
@Service
public class FreeDeliveryServiceImpl extends BaseServiceImpl<FreeDeliveryMapper, FreeDelivery, FreeDeliveryTableDef> implements FreeDeliveryService {

    @Override
    protected FreeDeliveryTableDef getTable() {
        return FreeDeliveryTableDef.freeDelivery;
    }

    @Override
    public Page<FreeDelivery> pageList(PageUtil pageUtil, String keyword, Integer type) {
        QueryCondition condition = QueryCondition.createEmpty();
        if (type != null)
            condition.and(table.type.eq(type));
        if (StringUtils.isNotBlank(keyword))
            condition.and(table.name.like(keyword));

        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.id.desc());

        return getMapper().paginateWithRelations(Page.of(pageUtil.getPage(), pageUtil.getRows()), wrapper);
    }

    @Override
    public boolean haveSameName(Long id, String name) {
        QueryCondition condition = table.name.eq(name);
        if (id != null)
            condition.and(table.id.ne(id));
        return exists(condition);
    }

    @Override
    public boolean updateEnabled(Long id, Integer enabled) {
        return UpdateChain.of(FreeDelivery.class)
                .set(table.enabled, enabled)
                .where(table.id.eq(id))
                .update();
    }

    @Override
    public List<FreeDelivery> listByEnabled() {
        return getMapper().selectListByCondition(table.enabled.eq(1));
    }
}
